#include "RateLimiter.h"

std::unordered_map<uint64_t, RateLimiter::LimitInfo> RateLimiter::s_limits;
std::mutex RateLimiter::s_mutex;

bool RateLimiter::allowOp(uint64_t key, int maxOps, int windowMs)
{
    std::lock_guard<std::mutex> lock(s_mutex);
    
    auto now = std::chrono::steady_clock::now();
    auto& info = s_limits[key];
    
    // 检查是否需要重置窗口
    auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
        now - info.windowStart
    ).count();
    
    if (elapsed >= windowMs) {
        // 新窗口
        info.windowStart = now;
        info.count = 1;
        return true;
    }
    
    // 在当前窗口内
    if (info.count < maxOps) {
        info.count++;
        return true;
    }
    
    // 超过限流阈值
    return false;
}

